package com.igeek.boot.controller;

import com.igeek.boot.common.Result;
import com.igeek.boot.service.SeckillService;
import com.igeek.boot.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.UUID;

/**
 *
 * 通过Redis实现秒杀
 *  1.秒杀页面，按钮，点击按钮可以进行秒杀操作
 *  2.秒杀动作：
 *       - stock库存， -1  直到为<=0
 *       - user用户 ， 存入秒杀成功的用户列表（每个用户只能秒杀成功一次）
 */
@RestController
@Slf4j
@RequestMapping("/kill")
public class SeckillController {

    @Autowired
    private SeckillService seckillService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public Result kill(Integer pid){
        String key = "seckill:count";
        Long increment = redisTemplate.opsForValue().increment(key);
        log.info(Thread.currentThread().getName()+" - 访问次数：{}" ,increment);

        //用户编号
        String uid = UUID.randomUUID().toString();

        //执行秒杀
        //Result result = seckillService.kill(pid , uid);
        //Result result = seckillService.killByTrans(pid, uid);
        Result result = seckillService.killByLua(pid + "", uid);
        return result;

    }
}
